package com.itheima.service.impl;

import com.aliyun.oss.OSS;
import com.itheima.config.AliyunConfig;
import com.itheima.entity.common.UploadResult;
import com.itheima.service.PicUploadService;
import com.itheima.utils.IdWorker;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class PicUploadServiceImpl implements PicUploadService {


    // 允许上传的格式
    private static final List<String> IMAGE_TYPE = Arrays.asList(".bmp", ".jpg", ".jpeg", ".png");

    @Autowired
    private OSS ossClient;
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private IdWorker idWorker;


    @Override
    public UploadResult upload(MultipartFile file, String type) {
        if (file == null ) {
            return new UploadResult(-1, "上传文件不能为空!");
        }
        // 对图片后缀名校验
        boolean isLegalCount = false;
        String filename = file.getOriginalFilename();
        // 获取图片后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (IMAGE_TYPE.contains(suffix)) {
            isLegalCount = true;
        }
        // 有非法格式的图片
        if (!isLegalCount) {
            return new UploadResult(-1, "上传的图片仅支持[.jpg, .jpeg, .png]等格式!");
        }

        // 文件新路径  type/images/年/月/日/xxx.jpg
        String filePath = getFileParth(filename, type);
        try {
            //  filePath 表示上传文件到OSS时需要指定包含文件后缀在内的完整目录路径，例如goods/2020/08/07/16866123.jpg
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            // 上传失败
            return new UploadResult(-1, "图片上传失败, 请稍后再试");
        }finally {
            ossClient.shutdown();
        }

        // 上传成功
        UploadResult result = new UploadResult(10000, "上传成功");
        result.setServerPath(aliyunConfig.getUrlPrefix() + filePath);
        result.setFilePath(filePath);
        result.setUid(idWorker.nextId() + "");
        return result;
    }


    private String getFileParth(String sourceFilename, String type) {
        if (StringUtils.isEmpty(type)) {
            type = "other";
        }
        DateTime dateTime = new DateTime();
        return type  + "/" + dateTime.toString("yyyy") + "/"
                + dateTime.toString("MM") + "/" + dateTime.toString("dd")
                + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999)
                + "." + StringUtils.substringAfterLast(sourceFilename, ".");
    }
}
